package com.zhou.service.impl;


import com.zhou.configure.PushConfigure;
import com.zhou.enums.WxStatusType;
import com.zhou.service.ValidateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.buf.HexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author lcz
 * @desc 验证实现类
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Service
@Slf4j
public class ValidateServiceImpl implements ValidateService {
    @Autowired
    private PushConfigure pushConfigure;

    @Override
    public String checkToken(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 签名
            String signature = request.getParameter("signature");
            if (StringUtils.isBlank(signature)) {
                return WxStatusType.FAIL.getType();
            }
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
            if (checkSignature(signature, timestamp, nonce)) {
                log.info("验证成功！echostr[{}]", echostr);
                return echostr;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return WxStatusType.FAIL.getType();
    }

    /**
     * 验证签名
     */
    public boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] infos = {pushConfigure.getToken(), timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(infos);
        StringBuilder content = new StringBuilder();
        for (String info : infos) {
            content.append(info);
        }
        String key = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            // 将加密后的byte数组转化成十六进制字符串
            key = HexUtils.toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return key != null && key.equals(signature);
    }
}
